package initialization

import (
	"fmt"
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
	"log"
)

func InitConsul(serviceName string, servicePort int) {
	cf := Config.Consul
	// 创建并初始化 Consul 客户端
	config := api.DefaultConfig()
	config.Address = fmt.Sprintf("%s:%d", cf.Hort, cf.Port) //地址
	consul, err := api.NewClient(config)
	if err != nil {
		log.Printf("初始化 Consul 客户端失败: %v", err)
	}
	// 创建健康检查配置
	check := &api.AgentServiceCheck{
		Interval:                       "5s",
		Timeout:                        "5s",
		GRPC:                           fmt.Sprintf("%s:%d", cf.Hort, cf.Port),
		DeregisterCriticalServiceAfter: "30s",
	}
	// 创建服务注册信息
	a := new(api.AgentServiceRegistration)
	a.ID = uuid.New().String()
	a.Name = serviceName
	a.Tags = []string{"GRPC"}
	a.Port = servicePort
	a.Address = "127.0.0.1"
	a.Check = check
	err = consul.Agent().ServiceRegister(a)
	if err != nil {
		log.Fatalf(err.Error())
	}
	log.Println("service register success")
}
